import { useCallback, useState } from "react";
import { runAutoFix } from "../lib/api/autoFix";
import type { AutoFixResult } from "../types/autoFix";
import { UI_STRINGS } from "../config/strings";

export function useAutoFix() {
  const [fixing, setFixing] = useState(false);
  const [result, setResult] = useState<AutoFixResult | null>(null);

  const triggerAutoFix = useCallback(async (files: File[]) => {
    if (!files.length) {
      alert(UI_STRINGS.alertUploadFirst);
      return;
    }
    setFixing(true);
    setResult(null);
    try {
      const data = await runAutoFix(files);
      if (!data.success) {
        throw new Error(data.error || "自动修复失败");
      }
      setResult(data);
    } catch (e: unknown) {
      console.error("auto-fix error", e);
      const msg = e instanceof Error ? e.message : String(e);
      alert(msg || "自动修复失败");
    } finally {
      setFixing(false);
    }
  }, []);

  const triggerIssueFix = useCallback(
    async (files: File[], issue: { file: string; line?: number; message?: string }) => {
      if (!files.length) {
        alert(UI_STRINGS.alertUploadFirst);
        return;
      }
      setFixing(true);
      setResult(null);
      try {
        const data = await runAutoFix(files, issue);
        if (!data.success) {
          throw new Error(data.error || "自动修复失败");
        }
        setResult(data);
      } catch (e: unknown) {
        console.error("auto-fix error", e);
        const msg = e instanceof Error ? e.message : String(e);
        alert(msg || "自动修复失败");
      } finally {
        setFixing(false);
      }
    },
    []
  );

  return { fixing, result, triggerAutoFix, triggerIssueFix } as const;
}
